
import { stringify } from 'qs';
import docCookies from '../common/DocCookies'

function loadXMLDoc() {
  if(docCookies.getItem('logout') == 'false') {
    if(global.menuData == undefined && docCookies.getItem('userId')) {
      const params = {
        userId: docCookies.getItem('userId'),
      };
      const url = `/api/system/user/showMenuByRole?${stringify(params)}`;
      var xmlhttp;
      if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
      }
      else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.open("GET", url, false);
      xmlhttp.setRequestHeader("Authorization", 'Bearer ' + docCookies.getItem('token'));
      xmlhttp.send();
      global.menuData = JSON.parse(xmlhttp.responseText).data;
    }
    return formatter(global.menuData);
  }else{
    return []
  }
}

function formatter (data, parentPath = '') {
  const list = [];
  if(data) {
    data.forEach((item) => {
      if (item.children) {
        list.push({
          ...item,
          path: `${parentPath}${item.path}`,
          children: formatter(item.children, `${parentPath}${item.path}/`),
        });
      } else {
        list.push({
          ...item,
          path: `${parentPath}${item.path}`,
        });
      }
    });
  }

  return list;
}

export const getMenuData = () => loadXMLDoc();
